package com.santoker.gateway.config;

import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.cloud.gateway.filter.ratelimit.RedisRateLimiter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Configuration
public class ServiceConfiguration {

    @Bean
    public RedisRateLimiter redisRateLimiter() {
        return new RedisRateLimiter(200, 500);
    }

    @Bean("userKeyResolver")
    public KeyResolver userKeyResolver() {
        return exchange -> {
            String token = this.getToken(exchange);
            if (StringUtils.isBlank(token)) {
                token = this.getIpAddress(exchange);
            }
            return Mono.just(token);
        };
    }

    private String getIpAddress(ServerWebExchange exchange) {
        return exchange.getRequest().getRemoteAddress().getAddress().getHostAddress();
    }

    private String getToken(ServerWebExchange exchange) {
        return exchange.getRequest().getHeaders().getFirst("token");
    }

}
